import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, AbstractControl } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { UserService } from '../_common/_service/user.service';
import { User } from '../_common/_model/user';
import { CookieService } from 'ng2-cookies';
import { AppConsts } from '../_common/consts';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  isLoginForm: boolean;
  loginForm: FormGroup;
  registerForm: FormGroup;
  isModelVisible = false;
  constructor(
    private _fb: FormBuilder,
    private _router: Router,
    private _consts: AppConsts,
    private _userService: UserService,
    private _message: NzMessageService,
    private _cookieService: CookieService) { }

  ngOnInit() {
    this.loginForm = this._fb.group({
      username: [null, [Validators.required, Validators.minLength(3), Validators.pattern('[a-zA-Z]\\w+')]],
      password: [null, [Validators.required, Validators.minLength(6)]]
    });
    this.registerForm = this._fb.group({
      // ? Validators.nullValidator how to use
      username: [null, [Validators.required, Validators.minLength(3), Validators.pattern('[a-zA-Z]\\w+')]],
      password: [null, [Validators.required, Validators.minLength(6)]],
      email: [null, [Validators.required, Validators.email]]
    });
  }

  //#region: get error message...
  getUsernameErrorMessageForLogin(): string {
    const control = this.loginForm.controls['username'];
    if (control.hasError('required')) {
      return ' - 请输入用户名';
    }
    if (control.hasError('minlength')) {
      return ' - 至少需要3个字符';
    }
    if (control.hasError('pattern')) {
      return ' - 用户名必须由字母开头且只包含字母、数字和下划线';
    }
  }

  getPasswordErrorMessageForLogin(): string {
    const control = this.loginForm.controls['password'];
    if (control.hasError('required')) {
      return ' - 请输入密码';
    }
    if (control.hasError('minlength')) {
      return ' - 至少需要6个字符';
    }
  }

  getUsernameErrorMessageForRegister(): string {
    const control = this.registerForm.controls['username'];
    if (control.hasError('required')) {
      return ' - 请输入用户名';
    }
    if (control.hasError('minlength')) {
      return ' - 至少需要3个字符';
    }
    if (control.hasError('pattern')) {
      return ' - 用户名必须由字母开头且只包含字母、数字和下划线';
    }
  }

  getPasswordErrorMessageForRegister(): string {
    const control = this.registerForm.controls['password'];
    if (control.hasError('required')) {
      return ' - 请输入密码';
    }
    if (control.hasError('minlength')) {
      return ' - 至少需要6个字符';
    }
  }

  getEmailErrorMessageForRegister(): string {
    const control = this.registerForm.controls['email'];
    const { required, email } = control.errors;
    if (control.hasError('required')) {
      return ' - 请输入邮箱';
    }
    if (control.hasError('email')) {
      return ' - 请输入正确的邮箱';
    }
  }
  //#endregion

  handleLogin(): void {
    this.isModelVisible = true;
    this.isLoginForm = true;
  }

  handleRegister(): void {
    this.isModelVisible = true;
    this.isLoginForm = false;
  }

  handleCancel(): void {
    this.isModelVisible = false;
    this.resetForms();
  }

  resetForms(): void {
    this.loginForm.reset();
    this.registerForm.reset();
  }

  // 获取LoginForm的控件实例
  getloginFormControl(name): AbstractControl {
    return this.loginForm.controls[name];
  }
  // LoginForm控件是否已经合法（检查之后）
  getLoginFormControlInvalid(controlName: string): boolean {
    const control = this.getloginFormControl(controlName);
    return control.dirty && control.invalid ? true : false;
  }
  // 获取RegisterForm的控件实例
  getRegisterFormControl(name): AbstractControl {
    return this.registerForm.controls[name];
  }
  // RegisterForm控件是否已经合法（检查之后）
  getRegisterFormControlInvalid(controlName: string): boolean {
    const control = this.getRegisterFormControl(controlName);
    return control.dirty && control.invalid ? true : false;
  }

  setCookie(name, value, expires) {
    return this._cookieService.set(name, value, expires);
  }

  onSubmit(isLoginForm: boolean): void {
    if (isLoginForm) {

      const controls = this.loginForm.controls;
      for (const i of Object.keys(controls)) {
        controls[i].markAsDirty();
      }
      if (this.loginForm.valid) {
        this._userService.login(this.loginForm.value)
          .subscribe(data => {
            const { token, ...userinfo } = data;
            const { access_token, expires_in } = token;
            this.setCookie(this._consts.authCookieName, access_token, expires_in);
            localStorage.setItem(this._consts.userLocalstorageName, JSON.stringify(userinfo));
            this._router.navigate(['/']);
          },
          ({ code, msg }) => {
            if (code && code === 4003) {
              this._message.error('用户名或密码输入有误');
            } else {
              this._message.error(msg);
            }
          });
      }

    } else {
      const controls = this.registerForm.controls;
      for (const i of Object.keys(this.registerForm.controls)) {
        controls[i].markAsDirty();
      }
      if (this.registerForm.valid) {
        const payload = {};
        Object.entries(controls).map(([k, v]) => {
          payload[k] = v.value;
        });
        this._userService.register(payload)
          .subscribe(data => {
            const { succ, code } = data;
            if (succ) {
              this._message.success('注册成功，请登陆。');
              setTimeout(() => {
                this.handleCancel();
                this.handleLogin();
              }, 2000);
            } else if (code === 2001) {
              this._message.error('该用户名已被注册。');
            }
          });
      }
    }
  }
}
